package com.enzo.pcms.login.controller;

import com.enzo.pcms.base.controller.BaseController;
import com.enzo.pcms.common.exception.DuplicateRecordException;
import com.enzo.pcms.common.util.ConsUtil;
import com.enzo.pcms.common.util.MsgUtil;
import com.enzo.pcms.login.model.User;
import com.enzo.pcms.login.service.UserService;
import com.itool.util.StringUtil;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Map;

@Controller
@RequestMapping(value="/user")
public class RegisterController extends BaseController {
    private static final Logger logger=Logger.getLogger(RegisterController.class);
    @Autowired
    private UserService userService;

    /**
     * 跳转注册页面
     * @param model
     * @return
     */
    @RequestMapping(value="/viewRegister")
    public String viewRegister(Map<String, Object> model) {
        return "register/register";
    }

    /**
     * 用户注册
     * @param request
     * @param response
     * @param user
     * @return
     */
    @RequestMapping(value="/signup")
    public ModelAndView signUp(HttpServletRequest request,HttpServletResponse response,User user) {
        viewName="register/register_info";
        String result="";
        if(user!=null&& StringUtil.isNotEmpty(user.getEmail())){
            try {
                String vCodeInput=request.getParameter("validcode");
                HttpSession session=request.getSession();
                String vCodeSession=(String)session.getAttribute("validcode");
                result=userService.signUp(user,vCodeInput,vCodeSession);
            } catch (Exception e) {
                if(e instanceof DuplicateRecordException){
                    result=MsgUtil.getValue(ConsUtil.MSG_REGISTER_EMAIL_EXIST);
                }else{
                    result=MsgUtil.getValue(ConsUtil.SYSTEM_ERROR);
                    logger.error(e.getMessage());
                }
            }
        }else{
            result=MsgUtil.getValue(ConsUtil.MSG_REGISTER_EMAIL_BLANK);
        }
        model.put("result", result);
        return getModelAndView();
    }

    /**
     * 注册激活
     * @param request
     * @param response
     * @param key 激活码
     * @return
     */
    @RequestMapping(value="/activate")
    public ModelAndView activate(HttpServletRequest request,HttpServletResponse response,String key){
        viewName="register/register_info";
        String result="";
        if(StringUtil.isNotEmpty(key)){
            try {
                result=userService.activateUser(key);
            } catch (Exception e) {
                result=MsgUtil.getValue(ConsUtil.SYSTEM_ERROR);
                logger.error(e.getMessage());
            }
        }
        model.put("result", result);
        return getModelAndView();
    }


    /**
     * 注册时验证邮箱是否已被注册
     * @param param
     * @param name
     * @return
     */
    @RequestMapping(value="/checkEmail",method=RequestMethod.POST)
    @ResponseBody
    public AvailabilityStatus checkEmail(@RequestParam String param,@RequestParam String name){
        try {
            userService.checkUserByNameOrEmail(null, param);
        } catch (Exception e) {
            if(e instanceof DuplicateRecordException){
                //表单验证插件特定的json数据格式｛"status":"y/n","info":"**"｝
                return new AvailabilityStatus("n",MsgUtil.getValue(ConsUtil.MSG_REGISTER_EMAIL_EXIST));
            }else{
                logger.error(MsgUtil.getValue(ConsUtil.SYSTEM_ERROR)+":"+e.getMessage());
                return new AvailabilityStatus("n",MsgUtil.getValue(ConsUtil.SYSTEM_ERROR));
            }
        }
        return new AvailabilityStatus("y",MsgUtil.getValue(ConsUtil.MSG_REGISTER_EMAIL_AVAILIABLE));
    }

    /**
     * 注册时验证校验码是否正确
     * @param request
     * @return
     */
    @RequestMapping(value="/checkValidCode")
    @ResponseBody
    public String checkValidCode(HttpServletRequest request){
        String code="";
        HttpSession session=request.getSession();
        code=(String)session.getAttribute("validcode");
        logger.info("validcode="+code);
        return code;
    }

    public UserService getUserService() {
        return userService;
    }

    public void setUserService(UserService userService) {
        this.userService = userService;
    }


}
